package me.stone.stanimeclient.page.catalog

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import me.stone.stanimeclient.core.common.extensions.mapKV
import me.stone.stanimeclient.core.data.domain.data.LoadCatalogListRepository
import me.stone.stanimeclient.core.data.util.AgeFanFilterDataUtils
import me.stone.stanimeclient.core.model.FilterTagItem
import javax.inject.Inject

@HiltViewModel
class CatalogViewModel @Inject constructor(
    private val repository: LoadCatalogListRepository
): ViewModel() {

    val filterData = flow {
        emit(AgeFanFilterDataUtils.commonData)
    }.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())

    private val mParamsState = MutableStateFlow<Map<String, FilterTagItem>>(emptyMap())

    val paramsStateData: Map<String, FilterTagItem>
        get() = mParamsState.value

    @OptIn(ExperimentalCoroutinesApi::class)
    val post = mParamsState
        .flatMapLatest { params ->
            Pager(PagingConfig(12)) {
                CatalogPagingSource(repository, params.mapKV { entry ->
                    entry.key to entry.value.tagValue
                })
            }.flow
        }
        .cachedIn(viewModelScope)

    val paramDisplay = mParamsState
        .map { param ->
            val display = param.values
                .map { item -> item.tagName }
                .filter { !it.contains("全部") }
                .joinToString(" · ")
            if (display.trim().isEmpty()) "全部" else display
        }
        .stateIn(viewModelScope, SharingStarted.Eagerly, "全部")

    @OptIn(ExperimentalCoroutinesApi::class)
    val totalCount = mParamsState
        .mapLatest { params ->
            val data = repository.loadCatalogList(
                page = 1,
                filters = params.mapKV { it.key to it.value.tagValue },
                pageSize = 1)
            "共 ${data.totalCount} 部番剧"
        }
        .stateIn(viewModelScope, SharingStarted.Lazily, "")

    fun putParams(item: FilterTagItem) = viewModelScope.launch {
        mParamsState.emit(mParamsState.value + (item.typeValue to item))
    }

}